package com.example.push.service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import io.micrometer.core.annotation.Timed;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@RequiredArgsConstructor
public class ScheduleTask {

    @Scheduled(fixedRate = 600000)
    @Timed(value = "task.schedule", longTask = true)
    public void run() {
        log.info("schedule start");
        ExecutorService executorService = Executors.newFixedThreadPool(8);
        // ExecutorService executorService = Context.taskWrapping(executorService);
        for (int i = 0; i < 100; i++) {
            executorService.submit(() -> {
                log.debug("findById thread={}", Thread.currentThread().getName());
                try {
                    TimeUnit.MILLISECONDS.sleep(200);
                } catch (InterruptedException e) {
                    log.error("findById error={}", e);
                }
            });
            if (i % 10 == 0) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    log.error("findById sleep error={}", e);
                }
            }
        }
        executorService.shutdown();
        try {
            while (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
                log.warn("task schedule runging...");
            }
        } catch (InterruptedException e) {
            log.error("error ", e);
        }
        log.info("schedule end");
    }
}
